package com.example.mybaseapp.ui

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.Settings
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.mybaseapp.R
import com.example.mybaseapp.util.InstallUtil
import com.shell.arc_scale_view.DownloadUtil
import kotlin.properties.Delegates

class DownLoadActivity : AppCompatActivity() {
    private val STORAGE_PERMISSION_CODE = 1
    private val permissions = arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE)
    var downloadUtil:DownloadUtil by Delegates.notNull()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_down_load)
        downloadUtil = DownloadUtil(this)
        findViewById<Button>(R.id.btn_down).setOnClickListener {
            checkPermission()
        }

            ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
    }
    val REQUEST_MANAGE_EXTERNAL_STORAGE = 12
    private fun checkPermission() {
        // 仅在 Android 11 (API Level 30) 及更高版本需要申请此权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            if (!Environment.isExternalStorageManager()) {
                // 检查并请求系统授权
                val intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION)
                    .setData(Uri.parse("package:$packageName"))
                startActivityForResult(intent, REQUEST_MANAGE_EXTERNAL_STORAGE)
//                ActivityCompat.requestPermissions(this, permissions, STORAGE_PERMISSION_CODE)
            }
            return
        }
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            // Permission already granted
            // Your code to handle the permission granted scenario
            startDownLoad()
        } else {
            // Permission not granted yet, request it
            ActivityCompat.requestPermissions(this, permissions, STORAGE_PERMISSION_CODE)
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == STORAGE_PERMISSION_CODE) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission granted, handle it here
                startDownLoad()
            } else {
                // Permission denied, handle this case
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_MANAGE_EXTERNAL_STORAGE) {
            // 检查是否授权成功
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                if (!Environment.isExternalStorageManager()) {
                    // 如果权限申请失败，处理相应逻辑（例如显示提示信息或退出应用）
                    // 在此可以添加用户提示或其他逻辑
                    Toast.makeText(
                        this,
                        "权限：MANAGE_EXTERNAL_STORAGE，没申请成功",
                        Toast.LENGTH_SHORT
                    ).show()
                } else {
                    startDownLoad()
                }

            }
        }
    }

    fun startDownLoad() {
        val url = "https://apkdl.sogouimecdn.com/wapdl/android/apk/SogouInput_11.47.3_android_sweb.apk?frm=new_pcjs_index"
        downloadUtil.downloadAPK(url,object:DownloadUtil.DownloadListener{
            override fun onProgressUpdate(progress: Int) {
               println( "onProgressUpdate: $progress")
            }

            override fun onDownloadComplete(fileUri: String) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    // 检查是否已获得安装未知来源应用的权限
                    if (!packageManager.canRequestPackageInstalls()) {
                        // 如果没有权限，引导用户到系统设置页面开启权限
                        val intent = Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES)
                        intent.data = Uri.parse("package:$packageName")
                        startActivity(intent)
                    }else{
                        InstallUtil().install(this@DownLoadActivity,fileUri)
                    }
                }

            }

            override fun onError(error: String) {

            }

        })
    }
}